<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <areas :area-type="areaType" :areas="treeAreas" v-on:handleNodeClick="onHandleNodeClick"/>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-card>
          <div class="filter-container">
            <el-select v-model="listQuery.unit" class="filter-item" clearable placeholder="单元号"
                       style="margin-left: 20px;width: 110px">
              <el-option
                v-for="item in units"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <el-input v-model="listQuery.floor" class="filter-item" clearable placeholder="楼层"
                      style="margin-left: 10px;width: 120px" type="number"></el-input>
            <el-input v-model="listQuery.room_number" class="filter-item" clearable placeholder="门牌号"
                      style="margin-left: 10px;width: 120px" type="number"></el-input>
            <el-input v-model="listQuery.device_number" class="filter-item" clearable
                      placeholder="终端编号" style="margin-left: 10px;width: 140px"></el-input>
            <el-select v-model.trim="listQuery.class" class="filter-item" clearable
                       placeholder="设备类型" style="margin-left: 10px;width: 110px">
              <el-option
                v-for="item in deviceTypes"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <el-button v-if="checkPermission('查询设备')" class="filter-item" icon="el-icon-search" style="margin-left:40px"
                       type="primary"
                       @click="getDeviceList">
              查询
            </el-button>
            <el-button v-if="checkPermission('导出设备')" :loading="btnLoading" class="filter-item"
                       icon="el-icon-download" style="margin-left: 10px" type="primary" @click="exportDevices">
              导出
            </el-button>
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              ref="equipTable"
              v-loading="listLoading"
              :cell-style="{padding:0+'px'}"
              :data="list"
              :row-style="{height:40+'px'}"
              border
              fit
              height="700"
              highlight-current-row
              stripe
              style="width: 100%;"
            >
              <el-table-column
                type="selection"
                width="40">
              </el-table-column>
              <el-table-column
                type="index"
                width="50">
              </el-table-column>
              <el-table-column align="center" label="终端编号">
                <template v-slot="{row}">
                  <span>{{ row.terminal_number }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="所属账户">
                <template v-slot="{row}">
                  <span>{{ row.user.username || '-'  }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="设备类型">
                <template v-slot="{row}">
                  <span>{{ row.class }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="设备版本" width="80">
                <template v-slot="{row}">
                  <span>{{ row.version }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="口径" width="80">
                <template v-slot="{row}">
                  <span>{{ row.size }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="最新抄表时间">
                <template v-slot="{row}">
                  <span>{{ formatDate(row.last_meter_time) }}</span>
                </template>
              </el-table-column>
              <el-table-column align="left" label="安装地址">
                <template v-slot="{row}">
                  <span>{{ row.install_address }}</span>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.page" :total="total"
                        @pagination="getDeviceList"/>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import areas from '@/components/area/AreaTree'
import AreaSelector from '@/components/area/AreaSelector'
import Pagination from '@/components/Pagination'
import {
  exportDevices,
  getDeviceList,
} from "@/api/device";
import {getCustomerList} from "@/api/customer";
import {getAreaTree} from "@/api/area";
import {checkPermission} from "@/utils/permission"
import moment from "moment";
import {exportExcel} from "@/utils/excel";
import XLSX from "xlsx";


export default {
  name: 'IMEIBlackList',
  components: {AreaSelector, areas, Pagination},
  data() {
    return {
      btnLoading: false,
      btnBatchLoading: false,
      tableKey: 0,
      exportData: [],
      listLoading: true,
      list: [],
      areaType: 2,
      temp: {
        id: 0,
        area_code: '',
        area_name: '',
        area_path: [],
        class: '',
        version: '',
        name: "",
        customer_id: '',
        size: 15,
        terminal_number: '',
        install_address: '',
        install_date: '',
        start_duration: 0,
        start_amount: 0,
        status: 0,
        is_allowed_close_cmd:false
      },
      treeAreas: [],
      oldDevice: {},
      total: 0,
      listQuery: {
        is_black_list:true,
        area_code: '',
        category: this.$store.getters.deviceCategory,
        device_number: '',
        class: '',
        unit: '',
        floor: '',
        room_number: '',
        is_contains_sub: this.$store.getters.showSubData,
        page: 1,
        pageSize: 20,
      },
      units: ['一单元', '二单元', '三单元', '四单元', '五单元', '六单元', '七单元', '八单元', '九单元', '十单元'],
      customerList: []
    };
  },
  created() {
    this.getDeviceList()
    this.getAreaTree()
  },
  computed: {
    deviceTypes() {
      const c  = this.$store.getters.deviceCategory
      return this.$store.getters.deviceType[c]
    }
  },
  methods: {
    checkPermission,
    exportDevices() {
      this.btnLoading = true
      const exportQueryData = Object.assign({}, this.listQuery)
      exportQueryData.pageSize = 5000
      getDeviceList(exportQueryData).then(response => {
        const headers = [
          '用户姓名','水司编号','用户类型','单元号',
          '楼层','室号','证件编号','设备类型','协议版本',
          '终端编号','口径尺寸','安装地址描述','安装时间',
          '初始流量','手机','是否启用下发关机指令'
        ]
        const cType = [{name: '居民', value: 1},{name: '商业', value: 2},{name: '工业', value: 3},{name: '民用', value: 4},{name: '其他', value: 0}]
        const data = response.data.list.map(item => ({
          用户姓名: item.customer ? item.customer.customer_name : '未知',
          水司编号: item.customer ? item.customer.refer_number: '未知',
          用户类型: item.customer ? cType.find(t => t.value === item.customer.customer_type).name : '未知',
          单元号: item.customer ? item.customer.unit : '未知',
          楼层: item.customer ? item.customer.floor : '未知',
          室号: item.customer ? item.customer.room_number : '未知',
          证件编号: item.customer? item.customer.identity_card : '未知',
          设备类型: item.class,
          协议版本: item.version,
          终端编号: item.terminal_number,
          口径尺寸: item.size,
          安装地址描述: item.install_address,
          安装时间: item.install_date,
          初始流量: item.start_amount,
          手机: item.customer? item.customer.mobile : '未知',
          是否启用下发关机指令: item.is_allowed_close_cmd ? '是' : '否',
        }))
        exportExcel(data, headers, '设备数据-'+moment().format('YYYYMMDD'))
        setTimeout(() => {
          this.btnLoading = false
        }, 1.5 * 1000)
      }).catch(err => {

      })
      this.listLoading = false
    },
    getAreaTree() {
      getAreaTree({type: 2,is_contains_sub:this.$store.getters.showSubData}).then(response => {
        this.treeAreas = response.data
      })
    },
    onHandleNodeClick: function (data) {
      if (this.listQuery.area_code !== data.code) {
        this.listQuery.area_code = data.code
        this.getDeviceList()
      }
    },
    getDeviceList() {
      this.listLoading = true
      let queryData = Object.assign({}, this.listQuery)
      queryData.device_size = queryData.device_size || 0
      getDeviceList(queryData).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    onSelectArea(data) {
      if (data !== '') {
        this.temp.area_path = data.path
        this.temp.area_code = data.value
        this.temp.area_name = data.pathLabels.join('/')
        getCustomerList({"area_code": this.temp.area_code,"page":1,"pageSize":1000}).then(response => {
          if (response.code === 20000) {
            this.customerList = response.data.list
          } else {
            this.$message.error('读取数据错误')
            this.customerList = []
          }
        })
      } else {
        this.temp.area_path = ''
        this.temp.area_code = ''
        this.temp.area_name = ''
        this.customerList = []
      }
    },
    handleReaderFile(file){
      this.batchUpdate.filename = file.name
      // 使用 FileReader 读取文件
      const reader = new FileReader();
      const that = this
      reader.onload = (e) => {
        const data = e.target.result;

        // 使用 XLSX 解析 Excel 文件内容
        const workbook = XLSX.read(data, { type: "binary" });

        // 获取第一个工作表的内容
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];

        // 将工作表内容解析为 JSON
        const fileData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        let rawData = fileData.slice(1);
        let filteredRows = rawData.filter((row) => {
          // 如果第八列不存在，或者为空字符串或 null/undefined，则过滤掉
          return row[9] !== undefined && row[9] !== null && row[9].toString().trim() !== "";
        });
        if (filteredRows.length === 0) {
          that.$message.error('批量更新最小设备数为1')
          return false
        }
        if (filteredRows.length > 100) {
          that.$message.error('批量更新最大设备数为100')
          return false
        }
        filteredRows = filteredRows.map((row) => row.map((cell) => String(cell || "")));
        that.batchUpdate.data = filteredRows;
      };

      // 以二进制方式读取文件
      reader.readAsBinaryString(file);

      // 阻止默认上传行为
      return false;
    },
    formatType(row) {
      let s = ''
      this.deviceTypes.forEach(function (type) {
        if (type.value === row.class) {
          s = type.label
        }
      })
      return s
    },
    formatDate(dateStr) {
      const d = moment(dateStr)
      if (d.millisecond() === 0) {
        return '-'
      }
      return d.format('YYYY-MM-DD')
    },
    resetTemp() {
      this.temp = {
        id: 0,
        area_code: '',
        area_name: '',
        area_path: [],
        class: '',
        version: '',
        name: "",
        customer_id: '',
        size: 15,
        install_address: '',
        install_date: '',
        start_amount: 0,
        status: 0,
        terminal_number: '',
        is_allowed_close_cmd:false
      }
    },
    resetQueryParams() {
      this.listQuery = {
        id: 0,
        page: 1,
        pageSize: 20,
        name: ''
      }
    }
  }
}
</script>
